//
//  WaterMarkTool.m
//  ShareExtensionDemo
//
//  Created by Elon on 2019/1/13.
//  Copyright © 2019 demo. All rights reserved.
//

#import "WaterMarkTool.h"


#define random(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)/255.0]
#define randomColor random(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256), 255)


@implementation WaterMarkTool

// 递归读取解压路径下的所有.png文件
+ (void)recursiveAddWaterMark:(NSString *) path title:(NSString *)title {
    
    BOOL isDir = NO;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir];
    if (isExist) {
        if (isDir) {
            NSArray * dirArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
            NSString * subPath = nil;
            for (NSString * str in dirArray) {
                subPath  = [path stringByAppendingPathComponent:str];
                BOOL issubDir = NO;
                [[NSFileManager defaultManager] fileExistsAtPath:subPath isDirectory:&issubDir];
                [self recursiveAddWaterMark:subPath title: title];
            }
        } else {
            
            NSString *fileName = [[path componentsSeparatedByString:@"/"] lastObject];
            if ([fileName hasSuffix:@".png"]) {
                NSLog(@"%@", path);
                UIImage *img = [UIImage imageWithContentsOfFile:path];
                if(img) {
                    NSLog(@"yyyy");
                }
                img = [self getWaterMarkImage:img andTitle:title andMarkFont:[UIFont boldSystemFontOfSize:44] andMarkColor:[randomColor colorWithAlphaComponent:waterMark_alpha]];
                NSLog(@"xxxx");
                [UIImagePNGRepresentation(img) writeToFile:path atomically:YES];
                NSLog(@"加水印成功!");
            }
        }
    }
}


/**
 根据目标图片制作一个盖水印的图片
 
 @param originalImage 源图片
 @param title 水印文字
 @param markFont 水印文字font(如果不传默认为23)
 @param markColor 水印文字颜色(如果不传递默认为源图片的对比色)
 @return 返回盖水印的图片
 */
+ (UIImage *)getWaterMarkImage: (UIImage *)originalImage andTitle: (NSString *)title andMarkFont: (UIFont *)markFont andMarkColor: (UIColor *)markColor {
    
    UIFont *font = markFont;
    if (font == nil) {
        font = [UIFont systemFontOfSize:63];
    }
    UIColor *color = markColor;
    if (color == nil) {
        color = [self mostColor:originalImage];
    }
    //原始image的宽高
    CGFloat viewWidth = originalImage.size.width;
    CGFloat viewHeight = originalImage.size.height;
    //为了防止图片失真，绘制区域宽高和原始图片宽高一样
    UIGraphicsBeginImageContext(CGSizeMake(viewWidth, viewHeight));
    //先将原始image绘制上
    [originalImage drawInRect:CGRectMake(0, 0, viewWidth, viewHeight)];
    //sqrtLength：原始image的对角线length。在水印旋转矩阵中只要矩阵的宽高是原始image的对角线长度，无论旋转多少度都不会有空白。
    CGFloat sqrtLength = sqrt(viewWidth*viewWidth + viewHeight*viewHeight);
    //文字的属性
    NSDictionary *attr = @{
                           //设置字体大小
                           NSFontAttributeName: font,
                           //设置文字颜色
                           NSForegroundColorAttributeName :color,
                           };
    NSString* mark = title;
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:mark attributes:attr];
    //绘制文字的宽高
    CGFloat strWidth = attrStr.size.width;
    CGFloat strHeight = attrStr.size.height;
    
    //开始旋转上下文矩阵，绘制水印文字
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //将绘制原点（0，0）调整到源image的中心
    CGContextConcatCTM(context, CGAffineTransformMakeTranslation(viewWidth/2, viewHeight/2));
    //以绘制原点为中心旋转
    CGContextConcatCTM(context, CGAffineTransformMakeRotation(CG_TRANSFORM_ROTATION));
    //将绘制原点恢复初始值，保证当前context中心和源image的中心处在一个点(当前context已经旋转，所以绘制出的任何layer都是倾斜的)
    CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-viewWidth/2, -viewHeight/2));
    
    //计算需要绘制的列数和行数
    int horCount = sqrtLength / (strWidth + HORIZONTAL_SPACE) + 1;
    int verCount = sqrtLength / (strHeight + VERTICAL_SPACE) + 1;
    
    //此处计算出需要绘制水印文字的起始点，由于水印区域要大于图片区域所以起点在原有基础上移
    CGFloat orignX = -(sqrtLength-viewWidth)/2;
    CGFloat orignY = -(sqrtLength-viewHeight)/2;
    
    //在每列绘制时X坐标叠加
    CGFloat tempOrignX = orignX;
    //在每行绘制时Y坐标叠加
    CGFloat tempOrignY = orignY;
    
    
    if(has_row_offset) {
        int i = 0;
        while(tempOrignX + strWidth <= sqrtLength &&
              tempOrignY + strHeight <= sqrtLength) {
            [mark drawInRect:CGRectMake(tempOrignX, tempOrignY, strWidth, strHeight) withAttributes:attr];
            tempOrignX += (strWidth + HORIZONTAL_SPACE);
            if (tempOrignX + strWidth > sqrtLength) {
                tempOrignX = orignX - strWidth/2 *i++;
                tempOrignY += (strHeight + VERTICAL_SPACE);
            }
        }
    }else {
        for (int i = 0; i < horCount * verCount; i++) {
            [mark drawInRect:CGRectMake(tempOrignX, tempOrignY, strWidth, strHeight) withAttributes:attr];
            if (i % horCount == 0 && i != 0) {
                tempOrignX = orignX;
                tempOrignY += (strHeight + VERTICAL_SPACE);
            }else{
                tempOrignX += (strWidth + HORIZONTAL_SPACE);
            }
        }
    }
    
    //根据上下文制作成图片
    UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGContextRestoreGState(context);
    return finalImg;
}

// 根据图片获取图片的主色调
+ (UIColor*)mostColor:(UIImage*)image {
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(image.size.width/2, image.size.height/2);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
    if (data == NULL) return nil;
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    
    for (int x=0; x<thumbSize.width; x++) {
        for (int y=0; y<thumbSize.height; y++) {
            int offset = 4*(x*y);
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
            if (alpha>0) {//去除透明
                if (red==255&&green==255&&blue==255) {//去除白色
                }else{
                    NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
                    [cls addObject:clr];
                }
                
            }
        }
    }
    CGContextRelease(context);
    //第三步 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    NSArray *MaxColor=nil;
    NSUInteger MaxCount=0;
    while ( (curColor = [enumerator nextObject]) != nil )
    {
        NSUInteger tmpCount = [cls countForObject:curColor];
        if ( tmpCount < MaxCount ) continue;
        MaxCount=tmpCount;
        MaxColor=curColor;
        
    }
    return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:([MaxColor[3] intValue]/255.0f)];
}

// 递归读取解压路径下的所有.png文件
+ (void)recursiveHandleSize:(NSString *) path width:(NSInteger ) toWidth {
    
    BOOL isDir = NO;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir];
    if (isExist) {
        if (isDir) {
            NSArray * dirArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
            NSString * subPath = nil;
            for (NSString * str in dirArray) {
                subPath  = [path stringByAppendingPathComponent:str];
                BOOL issubDir = NO;
                [[NSFileManager defaultManager] fileExistsAtPath:subPath isDirectory:&issubDir];
                [self recursiveHandleSize:subPath width: toWidth];
            }
        } else {
            NSString *fileName = [[path componentsSeparatedByString:@"/"] lastObject];
            
            if (![[fileName lowercaseString] hasSuffix:@".png"]) {
                return;
            }
            
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            CGFloat width = CGImageGetWidth(image.CGImage);
            CGFloat height = CGImageGetHeight(image.CGImage);
        
            CGFloat targetWidth = width;
            CGFloat targetHeight = height;
    
            if(width == height && width > toWidth) {
                targetWidth = toWidth;
                targetHeight = toWidth;
            }
            
            UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
            [image drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
            
            CGContextRef context = UIGraphicsGetCurrentContext();
            
            UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
            
            UIGraphicsEndImageContext();
            CGContextRestoreGState(context);
            
            [UIImagePNGRepresentation(finalImg) writeToFile:path atomically:YES];
        }
    }
}

// 递归读取解压路径下的所有.png文件
+ (void)recursiveScreeenShotHandleSize:(NSString *) path {
    
    BOOL isDir = NO;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir];
    if (isExist) {
        if (isDir) {
            NSArray * dirArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
            NSString * subPath = nil;
            for (NSString * str in dirArray) {
                subPath  = [path stringByAppendingPathComponent:str];
                BOOL issubDir = NO;
                [[NSFileManager defaultManager] fileExistsAtPath:subPath isDirectory:&issubDir];
                [self recursiveScreeenShotHandleSize:subPath];
            }
        } else {
            NSString *fileName = [[path componentsSeparatedByString:@"/"] lastObject];
            
            if (![[fileName lowercaseString] hasSuffix:@".png"]) {
                return;
            }
            
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            CGFloat width = CGImageGetWidth(image.CGImage);
            CGFloat height = CGImageGetHeight(image.CGImage);
            
            CGFloat targetWidth = width;
            CGFloat targetHeight = height;
            // 宽度：
            // 6p/7p/8p: 414*3 == 1242
            // 6/7/8: 375*2 == 750
            // 5/5s/5c/4/4s: 320*2 == 640
            // X: 375*3 == 1125
            
            if(width == 1242 || width == 750 || width == 1125) {
                targetWidth = width*960.0/height;
                targetHeight = 960;
            }else {
                return;
            }
            
            UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
            [image drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
            
            CGContextRef context = UIGraphicsGetCurrentContext();
            
            UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
            
            UIGraphicsEndImageContext();
            CGContextRestoreGState(context);
            
            [UIImagePNGRepresentation(finalImg) writeToFile:path atomically:YES];
        }
    }
}



+ (NSString *)typeForImageData:(NSData *)data {
    
    uint8_t c;
    [data getBytes:&c length:1];
    
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
        case 0x52: {
            //R as RIFF for WEBP
            if (data.length < 12) {
                return nil;
            }
            NSString *identifierTypeStr = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([identifierTypeStr hasPrefix:@"RIFF"] && [identifierTypeStr hasSuffix:@"WEBP"]) {
                return @"image/webp";
            }
            return nil;
        }
            
        default:
            break;
    }
    return nil;
}

@end
